import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/finally';

const URL: string = 'http://css.telecomjs.com';

@Injectable()
export class Api {

  constructor(public http: Http) {
  }

  get(endpoint: string, params?: any, options?: RequestOptions) {
    if (!options) {
      options = new RequestOptions();
    }

    // Support easy query params for GET requests
    if (params) {
      let p = new URLSearchParams();
      for (let k in params) {
        p.set(k, params[k]);
      }
      // Set the search field if we have params and don't already have
      // a search field set in options.
      options.search = !options.search && p || options.search;
    }

    return this.http.get(URL + '/' + endpoint, options);
  }

  // post(endpoint: string, body: any, options?: RequestOptions) {
  //   return this.http.post(URL + '/' + endpoint, body, options);
  // }

  post(endpoint: string, body: any, options?: RequestOptions) {
    return this.http.post(URL + '/' + endpoint, Api.getParams(body), options)
    .map(this.handleSuccess)
    .catch(this.handleError)
    .finally(this.handleComplete);
  }

  handleSuccess(response) {
    let res = response.json()
    if(res.retCode == '0') {
      res.success = true;
    } else {
      res.success = false;
    }
    return res;
  }

  handleError(error) {
    console.log(error);
    return error;
  }

  handleComplete() {

  }

  static getParams(paramMap): URLSearchParams {
    let params = new URLSearchParams();
    if (paramMap) {
      for (let key in paramMap) {
        let val = paramMap[key];
        if (val instanceof Date) {
          // val = Utils.dateFormat(val, 'yyyy-MM-dd hh:mm:ss')
        }
        params.set(key, val);
      }
    }
    params.set('latnId', '250');
    params.set('managerId', '250004086');
    params.set('token', 'ede65aaf299437c0369b35478669c23c');
    return params;
  }

  static getOptions(options): RequestOptions {
    if (!options) {
      options = new RequestOptions({
        headers: new Headers({
          'Content-Type': 'application/json; charset=UTF-8',
          'Accept': 'application/json;charset=utf-8'
        })
      });
      return options;
    }
  }
}
